package com.zly.functions;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.PrettyPrinter;
import com.fasterxml.jackson.core.util.DefaultPrettyPrinter;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class FunctionProviderBase {

    //Json中的路径分隔符
    protected static final char JSON_PATH_SEPARATOR = '/';

    protected static final ObjectMapper MAPPER = new ObjectMapper();

    //当前正在处理的JsonNode
    protected static JsonNode CUR_NODE;

    protected FunctionProviderBase(){}

    //获取指定路径Json文件的JsonNode对象
    protected static JsonNode readJsonNode(String jsonPathString){
        return readJsonNode(Path.of(jsonPathString));
    }

    protected static JsonNode readJsonNode(Path jsonPath){

        String jsonString = null;{
            try {
                jsonString = Files.readString(jsonPath);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        JsonNode node = null;{
            try {
                node = MAPPER.readTree(jsonString);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }

        return node;

    }

    //写入JsonNode到指定Json文件
    protected static void writeJsonNode(JsonNode node, String jsonPathString){
        //writeJsonNode(node,new File(jsonPathString));
        writeJsonNode(node,Path.of(jsonPathString));
    }

    protected static void writeJsonNode(JsonNode node, Path jsonPath){
        String content = node.toPrettyString();
        try {
            Files.writeString(jsonPath,content);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    /*
    protected static void writeJsonNode(JsonNode node, Path jsonPath){
        writeJsonNode(node,jsonPath.toFile());
    }

    private static void writeJsonNode(JsonNode node, File file){

        try {
            OBJECT_WRITER.writeValue(file,node);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

     */

    //设置当前正在处理的JsonNode
    public static void setCurNode(JsonNode curNode){
        CUR_NODE = curNode;
    }

}
